package com.jiawa.wiki.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiawa.wiki.domain.Content;
import com.jiawa.wiki.domain.Doc;
import com.jiawa.wiki.domain.DocExample;
import com.jiawa.wiki.exception.BusinessException;
import com.jiawa.wiki.exception.BusinessExceptionCode;
import com.jiawa.wiki.mapper.ContentMapper;
import com.jiawa.wiki.mapper.DocMapper;
import com.jiawa.wiki.mapper.DocMapperCust;
import com.jiawa.wiki.req.DocQueryReq;
import com.jiawa.wiki.req.DocSaveReq;
import com.jiawa.wiki.resp.DocQueryResp;
import com.jiawa.wiki.resp.PageResp;
import com.jiawa.wiki.util.CopyUtil;
import com.jiawa.wiki.util.RedisUtil;
import com.jiawa.wiki.util.RequestContext;
import com.jiawa.wiki.util.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author Li Cheng
 * @Date 2021/5/15 14:08
 * @Version 1.0
 */

@Service
public class DocService {
    //写日志
    private static final Logger LOG = LoggerFactory.getLogger(DocService.class);


    //相当于@Autowired
    @Resource
    private DocMapper docMapper;

    @Resource
    private DocMapperCust docMapperCust;

    @Resource
    private ContentMapper contentMapper;



    @Resource
    private SnowFlake snowFlake;


    @Resource
    private RedisUtil redisUtil;

    @Resource
    private WsService wsService;

    /**
     * 列表复制
     *
     * @param req
     * @return
     */
    public PageResp<DocQueryResp> list(DocQueryReq req) {
        DocExample docExample = new DocExample();
        DocExample.Criteria criteria = docExample.createCriteria();

        PageHelper.startPage(req.getPage(), req.getSize());
        List<Doc> docList = docMapper.selectByExample(docExample);


        PageInfo<Doc> pageInfo = new PageInfo<>(docList);
        LOG.info("总行数{}", pageInfo.getTotal());
        LOG.info("总页数{}", pageInfo.getPages());
        //List<DocResp> respList = new ArrayList<>();
        //for (Doc doc: docList) {
        //
        //    //对象复制
        //    DocResp docResp = CopyUtil.copy(doc, DocResp.class);
        //
        //    respList.add(docResp);
        //}
        List<DocQueryResp> list = CopyUtil.copyList(docList, DocQueryResp.class);

        PageResp<DocQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);


        return pageResp;

    }

    /**
     * 列表查询
     * @param
     * @return
     */
    public List<DocQueryResp> all(Long ebookId) {
        DocExample docExample = new DocExample();
        docExample.createCriteria().andEbookIdEqualTo(ebookId);
        docExample.setOrderByClause("sort asc");

        List<Doc> docList = docMapper.selectByExample(docExample);


        //列表复制
        List<DocQueryResp> list = CopyUtil.copyList(docList, DocQueryResp.class);

        return list;

    }

    /**
     * 保存
     *
     * @para
     * m req
     */
    @Transactional
    public void save(DocSaveReq req) {
        Doc doc = CopyUtil.copy(req, Doc.class);
        Content content = CopyUtil.copy(req, Content.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            //如果是空的则新增
            doc.setId(snowFlake.nextId());
            doc.setViewCount(0);
            doc.setVoteCount(0);

            docMapper.insert(doc);

            content.setId(doc.getId());
            contentMapper.insert(content);
        } else {

            //更新
            docMapper.updateByPrimaryKey(doc);
            int count = contentMapper.updateByPrimaryKeyWithBLOBs(content);
            if (count == 0){
                contentMapper.insert(content);
            }

        }
    }

    /**
     * 删除
     *
     * @param id
     */
    public void delete(Long id) {
       docMapper.deleteByPrimaryKey(id);
    }
    public void delete(List<String> ids) {
        DocExample docExample = new DocExample();
        DocExample.Criteria criteria = docExample.createCriteria();
        criteria.andIdIn(ids);
       docMapper.deleteByExample(docExample);
    }


    public String findContent(Long id) {

        Content content = contentMapper.selectByPrimaryKey(id);

        //文档阅读数+1
        docMapperCust.increaseViewCount(id);
        if(ObjectUtils.isEmpty(content)){
            return "";
        }else {

            return content.getContent();
        }

    }

    /**
     * 点赞
     * @param id
     */
    public void vote(Long id) {

        //远程IP+doc.id 作为key,24小时内不能重复
        String key = RequestContext.getRemoteAddr();
        if (redisUtil.validateRepeat("DOC_VOTE"+id+key,3600*24)) {
            docMapperCust.increaseVoteCount(id);
        }else {
            throw new BusinessException(BusinessExceptionCode.VOTE_REPEAT);
        }

        //推送点赞消息
        Doc docDb = docMapper.selectByPrimaryKey(id);
        String logId = MDC.get("LOG_ID");

        wsService.sendInfo("【"+docDb.getName()+"】被点赞!",logId);


    }



    public void updateEbookInfo() {
            docMapperCust.updateEbookInfo();
    }

}



























